package com.czy.lxtFX;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FilterDirtyData extends Application {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final String urlPrefix1 = "http://47.106.125.221:10079/zk_bathhouse_api/";//"http://47.106.125.221:10079/zk_bathhouse_api/";
    private final String urlPrefix2 = "http://8.129.1.179:10079/zk_bathhouse_api/";//"http://8.129.1.179:10079/zk_bathhouse_api/";
    private final String urlSuffixFilterDirtyData = "machine/filterDirtyDatas";
    final private String urlSuffixFlushDirtyData = "machine/getOpenFilterDirty";
    final private String urlSuffixSetSystemTime = "bathHouse/setSystemTime";
    final private String urlSuffixGetSystemTime = "bathHouse/getSystemTime";
    private final String bathHouseMode = "bathHouse";
    private final String nbMode = "nb";
    Stage primaryStage = null;
    private final Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    private final TextField schoolIdField = new TextField();
    private final TextField schoolInfoField = new TextField();
    private final TextArea infoText = new TextArea();
    private final DatePicker datePicker = new DatePicker(LocalDateTime.now().toLocalDate());
    private final TextField machineIdText = new TextField();

    @Override
    public void start(Stage stage) throws Exception {
        primaryStage = stage;
        infoText.setMaxSize(500, 200);
        infoText.setWrapText(true);//换行
        var root = new StackPane();
        stage.setTitle("乐校通过滤脏数据V1.5----------------------意见反馈QQ:1697946080");
        /*加窗口图标*/
        stage.getIcons().add(new Image(Thread.currentThread().getContextClassLoader().getResourceAsStream("cat.png")));
        var vBox = new VBox(6);
        /*学校id*/
        schoolIdField.setPromptText("请输入学校id，多个学校id用英文逗号分割");
        /*公共澡堂/NB|CAT1设备,开启/关闭过滤*/
        var switchBox = new HBox(4);
        var openBathhouse = new Button("开启");
        var closeBathhouse = new Button("关闭");
        var flushBathhouse = new Button("刷新");
        var exportBathhouse = new Button("导出");
        var openNB = new Button("开启");
        var closeNB = new Button("关闭");
        var flushNB = new Button("刷新");
        var exportNB = new Button("导出");
        switchBox.getChildren().addAll(new Text("公共澡堂："), openBathhouse, closeBathhouse, flushBathhouse, exportBathhouse
                , new Text("NB|CAT1设备："), openNB, closeNB, flushNB, exportNB);
        /*清空、根据学校名称得到学校id*/
        var schoolBox = new HBox(3);
        var clearSchool = new Button("清空");
        schoolInfoField.setPromptText("请输入学校名称或学校id");
        var schoolIdSearch = new Button("查询学校id");
        var schoolNameSearch = new Button("查询学校名称");
        var importSchool = new Button("从文件导入");
        schoolBox.getChildren().addAll(clearSchool, schoolInfoField, schoolIdSearch,schoolNameSearch, importSchool);
        /*提示框*/
        {
            alert.setTitle("关闭过滤提示");
            alert.setHeaderText("请确定是否关闭以下学校的过滤");
        }
        /*修改设备时间*/
        var updateTimeBox = new HBox(3);
        var updateTime = new Button("修改公共澡堂设备上传时间");
        datePicker.setPrefWidth(120);
        datePicker.setPromptText("请选择日期!");
        machineIdText.setPromptText("请输入设备id");
        updateTimeBox.getChildren().addAll(machineIdText, datePicker, updateTime);
        /*点击事件*/
        openBathhouse.setOnAction(event -> filter(bathHouseMode, 1));
        openNB.setOnAction(event -> filter(nbMode, 1));
        closeBathhouse.setOnAction(event -> {
            alert.setContentText(schoolIdField.getText());
            alert.showAndWait();
            ((Button) alert.getDialogPane().lookupButton(ButtonType.OK)).setOnAction(event1 -> {
                filter(bathHouseMode, 0);
            });
            ((Button) alert.getDialogPane().lookupButton(ButtonType.CANCEL)).setOnAction(event1 -> {
                schoolIdField.setText("");
            });
        });
        closeNB.setOnAction(event -> {
            alert.setContentText(schoolIdField.getText());
            alert.showAndWait();
            ((Button) alert.getDialogPane().lookupButton(ButtonType.OK)).setOnAction(event1 -> {
                filter(nbMode, 0);
            });
            ((Button) alert.getDialogPane().lookupButton(ButtonType.CANCEL)).setOnAction(event1 -> {
                schoolIdField.setText("");
            });
        });
        flushBathhouse.setOnAction(event -> flush(bathHouseMode));
        flushNB.setOnAction(event -> flush(nbMode));
        clearSchool.setOnAction(event -> clear());
        schoolIdSearch.setOnAction(event -> getSchoolIds());
        schoolNameSearch.setOnAction(event -> getSchoolName());
        updateTime.setOnAction(event -> updateTime());
        /*导出*/
        exportBathhouse.setOnAction(event -> {
            try (var out = new FileOutputStream(new File("./data_bathhouse.text"))) {
                out.write(schoolIdField.getText().getBytes(StandardCharsets.UTF_8));
                var alert2 = new Alert(Alert.AlertType.INFORMATION);
                alert2.setHeaderText("成功");
                alert2.show();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        exportNB.setOnAction(event -> {
            try (var out = new FileOutputStream(new File("./data_nb.text"))) {
                out.write(schoolIdField.getText().getBytes(StandardCharsets.UTF_8));
                var alert2 = new Alert(Alert.AlertType.INFORMATION);
                alert2.setHeaderText("成功");
                alert2.show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        /*导入文件中的数据*/
        importSchool.setOnAction(event -> {
            var fileChooser = new FileChooser();
            fileChooser.setInitialDirectory(new File("."));
            var file = fileChooser.showOpenDialog(new Stage());
            if (file != null) {
                try (var in = new FileInputStream(file)) {
                    schoolIdField.setText(new String(in.readAllBytes(), StandardCharsets.UTF_8));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        vBox.getChildren().addAll(schoolIdField, switchBox, schoolBox, infoText, updateTimeBox);
        root.getChildren().add(vBox);
        stage.setScene(new Scene(root, 600, 300));
        stage.show();
    }

    public void updateTime() {
        var localDate = datePicker.getValue();
        var machineId = machineIdText.getText();
        if (localDate == null) {
            changePromptColor(datePicker, "red");
            return;
        }
        if (machineId.strip().equals("")) {
            changePromptColor(machineIdText, "red");
            return;
        }
        if (localDate.isAfter(LocalDateTime.now().toLocalDate())) {
            infoText.setText("不能大于当前时间");
            infoText.setStyle("-fx-fill:red;");
            return;
        }
        /*HHmmssSSS*/
        var systemTime = DateTimeFormatter.ofPattern("yyyyMMdd").format(localDate)+"000000000";
        changePromptColor(machineIdText, "gray");
        changePromptColor(datePicker, "gray");
        Stream.iterate(0, i -> i + 1).limit(3).forEach((i) -> {
            HttpRequestUtil.sendGet(urlPrefix1 + urlSuffixSetSystemTime, false, "machineId=" + machineId + "&systemTime=" + systemTime);
            HttpRequestUtil.sendGet(urlPrefix2 + urlSuffixSetSystemTime, false, "machineId=" + machineId + "&systemTime=" + systemTime);
        });
        clear();
        String result1 = HttpRequestUtil.sendGet(urlPrefix1 + urlSuffixGetSystemTime, false, "machineId=" + machineId);
        String result2 = HttpRequestUtil.sendGet(urlPrefix2 + urlSuffixGetSystemTime, false, "machineId=" + machineId);
        Map<String, Object> resultData1 = str2Map(result1);
        Map<String, Object> resultData2 = str2Map(result2);
        String info = Integer.valueOf(String.valueOf(resultData1.get("Code"))) == 0 ? resultData1.get("Data").toString() : resultData1.get("Message").toString();
        info += ":" + (Integer.valueOf(String.valueOf(resultData2.get("Code"))) == 0 ? resultData2.get("Data").toString() : resultData2.get("Message").toString());
        infoText.setText(info);
    }

    public void clear() {
        schoolIdField.clear();
        schoolInfoField.clear();
        infoText.setText("");
        machineIdText.clear();
        changePromptColor(schoolInfoField, "gray");
        changePromptColor(schoolIdField, "gray");
        changePromptColor(machineIdText, "gray");
        changePromptColor(datePicker, "gray");
    }

    public void getSchoolIds() {
        var schoolName = schoolInfoField.getText();
        if (StringUtil.isBlank(schoolName)) {
            changePromptColor(schoolInfoField, "red");
            return;
        }
        changePromptColor(schoolInfoField, "gray");
        String[] schoolURLS = new String[]{
                "http://a_web.lxt6.cn:8089/PayPlatform/GetSchoolList"
                , "http://b_web.lxt6.cn:8089/PayPlatform/GetSchoolList"
                , "http://c_web.lxt6.cn:8089/PayPlatform/GetSchoolList"
                , "http://d_web.lxt6.cn:8089/PayPlatform/GetSchoolList"
                , "http://huanong.lexiaotong.cn:8089/PayPlatform/GetSchoolList"
        };
        var infos=new ArrayList<Map<String,String>>();
        for (String schoolURL : schoolURLS) {
            String result = HttpRequestUtil.sendGet(schoolURL, false, "");
            var dataList = str2List(result);
            dataList.removeIf(map -> !map.get("Name").contains(schoolName)||infos.contains(map.get("Name")));
            infos.addAll(dataList);
        }
        if (!infos.isEmpty()) {
            infoText.setText(infos.toString());
            schoolIdField.setText(infos.stream().map(map -> map.get("ID")).collect(Collectors.joining(",")));
            return;
        }
    }
    public void getSchoolName() {
        var schoolId = schoolInfoField.getText().strip();
        if (StringUtil.isBlank(schoolId)) {
            changePromptColor(schoolInfoField, "red");
            return;
        }
        changePromptColor(schoolInfoField, "gray");
        String[] schoolURLS = new String[]{
                "http://a_web.lxt6.cn:8089/PayPlatform/GetSchoolList"
                , "http://b_web.lxt6.cn:8089/PayPlatform/GetSchoolList"
                , "http://c_web.lxt6.cn:8089/PayPlatform/GetSchoolList"
                , "http://d_web.lxt6.cn:8089/PayPlatform/GetSchoolList"
                , "http://huanong.lexiaotong.cn:8089/PayPlatform/GetSchoolList"
        };
        for (String schoolURL : schoolURLS) {
            String result = HttpRequestUtil.sendGet(schoolURL, false, "");
            var dataList = str2List(result);
            var schoolInfoTempOption=dataList.stream().filter(map->map.get("ID").contains(schoolId)).findFirst();
            if (schoolInfoTempOption.isPresent()){
                infoText.setText(schoolInfoTempOption.get().toString());
                return;
            }
        }
        infoText.setText("未查到对应的学校信息！");
    }

    public void filter(String mode, Integer status) {
        if (!StringUtil.containNum(schoolIdField.getText())) {
            changePromptColor(schoolIdField, "red");
            schoolIdField.setText("");
            return;
        }
        String schoolIds = StringUtil.erase(schoolIdField.getText(), "[^0-9,]");
        if (StringUtil.isBlank(schoolIds)) {
            changePromptColor(schoolIdField, "red");
            schoolIdField.setText("");
            return;
        }
        changePromptColor(schoolIdField, "gray");
        Stream.iterate(0, i -> i + 1).limit(3).forEach((i) -> {
            HttpRequestUtil.sendGet(urlPrefix1 + urlSuffixFilterDirtyData, false, "mode=" + mode + "&status=" + status + "&schoolIds=" + schoolIds);
            HttpRequestUtil.sendGet(urlPrefix2 + urlSuffixFilterDirtyData, false, "mode=" + mode + "&status=" + status + "&schoolIds=" + schoolIds);
        });
        if (!flush(mode)) {
//            filter(mode,status);
        }
    }

    /*两个集合相等时返回true*/
    public Boolean flush(String mode) {
        String result1 = HttpRequestUtil.sendGet(urlPrefix1 + urlSuffixFlushDirtyData, false, "mode=" + mode);
        String result2 = HttpRequestUtil.sendGet(urlPrefix2 + urlSuffixFlushDirtyData, false, "mode=" + mode);
        Map<String, Object> resultData1 = str2Map(result1);
        Map<String, Object> resultData2 = str2Map(result2);
        if (resultData1.get("Data") instanceof Map) {
            schoolIdField.setText("服务端报错：" + result1);
            return false;
        }
        List<String> data1 = (List<String>) resultData1.get("Data");
        List<String> data2 = (List<String>) resultData2.get("Data");
        data1.sort((o1, o2) -> {
            if (StringUtil.isBlankOr(o1, o2)) {
                return 0;
            }
            return o1.compareTo(o2);
        });
        data2.sort((o1, o2) -> {
            if (StringUtil.isBlankOr(o1, o2)) {
                return 0;
            }
            return o1.compareTo(o2);
        });
        schoolIdField.setText(data1 + "," + data2);
        return data1.stream().allMatch(data2::contains);
    }

    public void changePromptColor(Node node, String color) {
        node.setStyle("-fx-prompt-text-fill:" + color + ";");
    }

    private Map<String, Object> str2Map(String data) {
        try {
            return objectMapper.readValue(data, Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return Collections.emptyMap();
        }
    }

    private List<Map<String, String>> str2List(String data) {
        try {
            return objectMapper.readValue(data, List.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return Collections.emptyList();
        }
    }
}
